package com.homework.loans;

import org.joda.time.DateTime;

import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.util.List;

import static com.google.common.collect.Lists.newArrayList;
import static java.math.BigDecimal.valueOf;
import static java.util.Optional.ofNullable;
import static javax.persistence.GenerationType.AUTO;

/**
 * Loan domain object.
 *
 * @author Blind
 */
@Entity @Table public class Loan {
    public static final BigDecimal MAX_AMOUNT = valueOf(10000);

    @Id @GeneratedValue(strategy = AUTO) public Integer id;
    @Column public BigDecimal amount;
    @Column(name = "start_date") public DateTime startDate;
    @Column public Integer duration;
    @Column public String ip;
    @NotNull @ManyToOne public Customer customer;
    @OneToMany(cascade=CascadeType.ALL) public List<LoanExtension> extensions = newArrayList();

    /**
     * Get loan interest, it depends upon sum and extension I suppose.
     *
     * Sum  * extension number * 1.5
     */
    public int interest() {
        return ofNullable(amount).map(a -> a.add(valueOf(extensions.stream().count() * 1.5))).
                orElse(BigDecimal.ZERO).intValue();
    }
}
